package com.tencent.sr.iris.activity.service.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import java.util.Collections;
import java.util.List;

@Slf4j
public class ESUtils {

    /**
     * 处理es返回结果
     *
     * @param searchResponse
     * @return
     */
    public static <T> List<T> buildResponse(SearchResponse searchResponse, Class<T> clazz) {
        JSONArray jsonArray = new JSONArray();
        if (searchResponse == null) {
            log.error("es查询结果为null");
            return jsonArray.toJavaList(clazz);
        }
        SearchHits hits = searchResponse.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            JSONObject jsonObject = JSON.parseObject(sourceAsString);
            jsonArray.add(jsonObject);
        }
        return jsonArray.toJavaList(clazz);
    }

    /**
     * 处理es返回结果
     *
     * @param searchResponse
     * @return
     */
    public static <T> List<T> getFieldList(SearchResponse searchResponse, String fieldName, Class<T> clazz) {
        if (searchResponse == null) {
            log.error("es查询结果为null");
            return Collections.emptyList();
        }
        JSONArray jsonArray = new JSONArray();
        SearchHits hits = searchResponse.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            JSONObject jsonObject = JSON.parseObject(sourceAsString);
            jsonArray.add(jsonObject.get(fieldName));
        }
        return jsonArray.toJavaList(clazz);
    }

}
